
var pagesrc="unknow";
var userid="";//Math.floor((Math.random()*1000000)+1);
var page=document.URL;
var startTime = new Date();

//get referer domain
var ref=document.referrer;
var domainref="";
if(ref!=undefined && ref!=""){
	var arrdomain=ref.match(/^http([s]?):\/\/([a-zA-Z0-9-_\.]+)(:[0-9]+)?/);
	if(arrdomain.length>2)domainref=arrdomain[2];
}
//get url params
var urlParams;
(window.onpopstate = function () {
    var match,
        pl     = /\+/g,  // Regex for replacing addition symbol with a space
        search = /([^&=]+)=?([^&]*)/g,
        decode = function (s) { return decodeURIComponent(s.replace(pl, " ")); },
        query  = window.location.search.substring(1);

    urlParams = {};
    while (match = search.exec(query))
       urlParams[decode(match[1])] = decode(match[2]);
})();
checkCookie();

//on exist tracking
window.onbeforeunload = function (e) {
	  var e = e || window.event;

	  //IE & Firefox
	  if (e) {
	    leavepagetrack();
	  }
	  else{
	  // For Safari
	  leavepagetrack();
	  }
	};

	function leavepagetrack(){
		var endTime = new Date();
		var timeDiff = endTime - startTime;
		 ga('send', 'event', pagesrc,userid,page,timeDiff/1000);		 
		}
	function setCookie(cname,cvalue,exdays,ispath,isdomain)
	{
	var d = new Date();
	var expires="";
	if(exdays!=undefined && exdays>0){
		d.setTime(d.getTime()+(exdays*24*60*60*1000));
		expires = ";expires="+d.toGMTString();
	}
	var path="";
	if(ispath!=undefined && ispath>0)
		path=";path=/";
	var domain="";
	if(isdomain!=undefined && isdomain>0)
		domain=";domain=."+document.URL.match(/^http([s]?):\/\/([a-zA-Z0-9-_\.]+)(:[0-9]+)?/)[2];
	document.cookie = cname + "=" + cvalue + expires +path;
	}

	function getCookie(cname)
	{
	var name = cname + "=";
	var ca = document.cookie.split(';');
	for(var i=0; i<ca.length; i++) 
	  {
	  var c = ca[i].trim();
	  if (c.indexOf(name)==0) return c.substring(name.length,c.length);
	}
	return "";
	}

	function checkCookie()
	{
		//check userid
		if(getCookie("userid")!=""){
			userid=getCookie("userid");
		}
		else{
			userid=Math.floor((Math.random()*1000000)+1);
			setCookie("userid",userid,0,1,1);
		}
		//check pagesrc
		if(getCookie("pagesrc")!=""){
			pagesrc=getCookie("pagesrc");
		}
		else{
			pagesrc="unknow";
			if(urlParams['src']!=undefined && urlParams['src']!=""){
				pagesrc=urlParams['src'];
			}
			else if(domainref!=undefined && domainref!=""){
				pagesrc=domainref;
			}	
		
			setCookie("pagesrc",pagesrc,0,1,1);
		}
	}